package com.zhuifeng.search.service.impl;


import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhuifeng.common.core.domain.R;
import com.zhuifeng.common.core.utils.StringUtils;
import com.zhuifeng.search.client.GulimallElasticSearchConfig;
import com.zhuifeng.search.domain.Product;
import com.zhuifeng.search.domain.request.ProductRequest;
import com.zhuifeng.search.result.PageResult;
import com.zhuifeng.search.result.Result;
import com.zhuifeng.search.service.ProdoctService;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ProdoctServiceImpl implements ProdoctService {
    private final String INDEX_NAME = "product_info";

    private final RestHighLevelClient client;

    public ProdoctServiceImpl() {
        GulimallElasticSearchConfig gulimallElasticSearchConfig = new GulimallElasticSearchConfig();
        this.client = gulimallElasticSearchConfig.esRestClient();
    }
    @Override
    public Result<PageResult<Product>> productInfoList(ProductRequest productRequest) {
//        创建数组
        List<Product> productList = new ArrayList<>();
//        total
        long total = 0;

        try {

            SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
//            接收条件
            if (StringUtils.isNotEmpty(productRequest.getAllName())) {
//                赋值给商品名称
                MatchQueryBuilder productName = QueryBuilders.matchQuery("productName", productRequest.getAllName());

                boolQueryBuilder.should(productName);
//                赋值给商品名称
                MatchQueryBuilder typeName = QueryBuilders.matchQuery("typeName", productRequest.getAllName());

                boolQueryBuilder.should(typeName);
            }
//            接收条件
            if (StringUtils.isNotEmpty(productRequest.getBrandId())) {
                MatchQueryBuilder brandId = QueryBuilders.matchQuery("brandId", productRequest.getBrandId());

                boolQueryBuilder.must(brandId);
            }

//            高亮
            HighlightBuilder highlightBuilder = new HighlightBuilder();
//            获取字段
            highlightBuilder.field("productName");
//            span标签
            highlightBuilder.preTags("<span style=\'color : red\'>");
            highlightBuilder.postTags("</span>");

            searchSourceBuilder.highlighter(highlightBuilder);
//            分页
            searchSourceBuilder.from((productRequest.getNumPage() - 1 )* productRequest.getSizePage());
//            条数
            searchSourceBuilder.size(productRequest.getSizePage());


            searchSourceBuilder.query(boolQueryBuilder);
            searchRequest.source(searchSourceBuilder);


            SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);

            SearchHits searchResponseHits = search.getHits();

            TotalHits totalHits = searchResponseHits.getTotalHits();

            total = totalHits.value;

            SearchHit[] hits = searchResponseHits.getHits();

            for (SearchHit hit : hits) {
                String productString = hit.getSourceAsString();

                Product product = JSON.parseObject(productString, Product.class);
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();

                if (highlightFields!= null && highlightFields.size() != 0) {
                    HighlightField productName = highlightFields.get("productName");

                    if (productName != null) {
                        Text[] fragments = productName.getFragments();
                        String str = "";

                        for (Text fragment : fragments) {
                            str += fragment;
                        }
//                        赋值
                        product.setProductName(str);
                    }
                }
//                赋值
                product.setProductId(hit.getId());
                productList.add(product);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        Result<PageResult<Product>> pageResultResult = PageResult.toResult(total, productList);

        return pageResultResult;
    }
}
